package com.dayuanit.dy15.atm.controller;

import com.dayuanit.dy15.atm.captcha.GifCaptcha;
import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

@RestController

public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Value("${atm.user.avatar.path}")
    private String avatarPath;



    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public ResponseDTO register(String username, String pwd, String confirmPwd, String code, HttpSession session) {
        if (StringUtils.isBlank(code)) {
            return ResponseDTO.fail("请输入验证码");
        }

        //从session中获取验证码和用户输入的验证码做比较
        String captchaCode = (String)session.getAttribute("captchaCode");
        //验证码不区分大小写  还有 比较的时候拿常量和变量比 防止NPE异常
        if (!code.equalsIgnoreCase(captchaCode)) {
            return ResponseDTO.fail("验证码错误");
        }

        userService.register(username, pwd, confirmPwd);
        return ResponseDTO.sucess();
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ResponseDTO login(String username, String password, HttpSession session) {
        //敏感信息不要打印在日志里。
//        logger.info("用户登录 username={}, password={}", username, password);

        User user = userService.login(username, password);
        savaUserStatus(user, session);
        return ResponseDTO.sucess();
    }

    @RequestMapping("/user/logout")
    public ResponseDTO logout(HttpSession session) {
        session.removeAttribute("loginUser");
        session.invalidate();
        return ResponseDTO.sucess();
    }

    @RequestMapping("/captcha/createCaptcha")
    public void createCaptcha(HttpServletResponse response, HttpSession session) {
        GifCaptcha gifCaptcha = new GifCaptcha();
        try {
            gifCaptcha.out(response.getOutputStream());
            String captchaCode = gifCaptcha.text();
            System.out.println("captchaCode=" + captchaCode);

            //将生成的验证码存到session中，注册的时候会用到
            session.setAttribute("captchaCode", captchaCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/user/resetPwd")
    public ResponseDTO resetPwd(String oldPwd, String newPwd, String confirmPwd, HttpServletRequest request) {
        userService.resetPwd(getUserId(request), oldPwd, newPwd, confirmPwd);
        // 退出
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute("loginUser");
            session.invalidate();
        }
        return ResponseDTO.sucess();
    }

    @RequestMapping("/user/uploadAvatar")
    public void uploadAvatar(MultipartFile avatar, HttpServletRequest request, HttpServletResponse response) {
        if (avatar.isEmpty()) {
            return;
        }

        try {
            String filePath = avatarPath + getUserId(request);

            byte[] bytes = avatar.getBytes();
            try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);) {
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
            }

            OutputStream out = response.getOutputStream();
            //响应一个js，调用父窗口的函数 注意 加上parent指定调用父窗口的函数
            out.write("<script>parent.uploadCallBack();</script>".getBytes());
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/user/showAvatar")
    public void showAvatar(HttpServletRequest request, HttpServletResponse response) {
        try {
            OutputStream out = response.getOutputStream();

            byte[] buff = new byte[1024];
            int length = -1;
            FileInputStream fileInputStream = new FileInputStream(avatarPath + getUserId(request));
            while (-1 != (length = fileInputStream.read(buff))) {
                out.write(buff, 0, length);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
